require "torrent-ruby"
class Attach
  include Mongoid::Document
  include Mongoid::Timestamps
  field :name
  field :format, :default => "torrent"
  # 屏幕高度，480, 481 ,720,1080,3000
  field :quality, :type => Integer, :default => 0
  field :url
  field :file_size, :type => Integer
  field :movie_id ,:type => Integer
  belongs_to :movie
  attr_accessor :file


  validates :quality, :inclusion => { :in => [0,480,481,720,1080,3000] }
  validates :url, :uniqueness => true, :format => { :with => /(thunder|ed2k|magnet|http|ftp):/i, :on => :create }
  mount_uploader :file, AttachUploader

  before_validation :fix_format
  #当添加附件后，需要将这个影片的属性值修改成可以显示在列表页面
  after_create :verify
  #如果是这个影片没有资源,需要将影片的的验证设置为不通过
	after_destroy :guess

  index({ :movie_id => 1,:url => 1}, { :unique => true,:background=>true })
  index({ url: 1 }, { unique: true, background: true })

  #default_scope -> desc(:quality)
  default_scope -> { order(quality: :desc,file_size: :desc) }
  #scope :default, -> { desc(:quality,:file_size) }



  def  self.has_quality_by_title(title)
    qu = title.match(/480p|720p|1080p|480P|720P|1080P|蓝光/i)
    qu = qu.to_s.downcase.delete('p')
    qu = '0' if qu.blank?
    qu = '3000' if qu=='蓝光'
    return qu
  end



  def self.read_torrent(file_name)
    info = nil
    begin
      info = TorrentFile.open(file_name).to_h["info"]
    rescue => e
      Rails.logger.warn { "[ERROR] read_torrent : #{e} " }
      return info
    end
    unless info["files"].blank?
      total_length = info["files"].collect { |f| f["length"] }.sum
      file_name = info["name.utf-8"].blank? ? info["name"] : info["name.utf-8"]
    else
      total_length = info["length"].to_f
      file_name = info["name"]
    end

    hex_diegst = Digest::SHA1.hexdigest(info.bencode)
    file_name = file_name.force_encoding("utf-8")
    url = "magnet:?xt=urn:btih:#{hex_diegst}&dn=#{file_name}"
    [file_name, total_length, url]
  end

  protected

	def verify
		@movie = self.try(:movie)
		@movie.update(:verified => true) if @movie.verified == false
	end

	def guess
		@movie = self.try(:movie)
		@movie.update(:verified => false) if @move.attachs.blank?
	end

  def fix_format
    if !self.url.blank?
      protocol = self.url.split(":").first.downcase.strip
      case protocol
      when "thunder"
      when "http"
        self.format = "thunder"
      else
        self.format = protocol
      end
    else
    end
  end
end
